﻿#include "FileTransferServer.h"
#include <QTcpServer>
#include <QSslSocket>
#include <QThread>
#include <QtNetwork>
#include <QDebug>
#include "CatThreadPool.h"



FileTransferServer::FileTransferServer(QObject *parent)
    : QTcpServer(parent)
    , m_pCatThreadPool(nullptr)
{
    InitProperty();
}

FileTransferServer::~FileTransferServer()
{

}

void FileTransferServer::InitProperty()
{
    m_pCatThreadPool = new CatThreadPool(this);
    qDebug() << "ThreadPool: " << m_pCatThreadPool->GetThreadCount();

    qDebug() << "thread_id: " << QThread::currentThread();

    connect(this, &QTcpServer::acceptError, this, [=](){
        qDebug() << "acceptError";
    });


}

void FileTransferServer::Listen(const QHostAddress &address, quint16 port)
{
    if(!this->isListening())
    {
        this->listen(address, port);
    }
}

void FileTransferServer::incomingConnection(qintptr handle)
{
    int socketDescriptor = static_cast<int>(handle);

    m_pCatThreadPool->AddTask([=](){
        bool *m_bactivity = new bool;
        *m_bactivity = true;
        QTcpSocket *socket = new QTcpSocket;
        if(!socket->setSocketDescriptor(socketDescriptor))
        {
            return;
        }
        // 客户端断开事件
        connect(socket, &QTcpSocket::disconnected, [=](){
            *m_bactivity = false;
            socket->disconnect();
        });

        // 业务处理
        connect(socket, &QTcpSocket::readyRead, [=](){
            *m_bactivity = true;
            QString data = socket->readAll();
            qDebug() << data;
            socket->write(data.toUtf8());
        });

        // 处理非活动链接
        while(*m_bactivity)
        {
            if(*m_bactivity)
            {
                *m_bactivity = false;
                socket->waitForDisconnected(1800*1000);
            }
        }

        socket->close();
        socket->deleteLater();

    });

    qDebug() << "ThreadPoolWorkCount: " << m_pCatThreadPool->GetThreadWorkCount();

    emit newConnection();
}
